package com.anji.plus.gaea.introspector;

import com.anji.plus.gaea.constant.GaeaConstant;
import com.anji.plus.gaea.holder.UserContentHolder;
import com.anji.plus.gaea.utils.GaeaDateUtils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * 后端返回前端 时间序列号
 * @author: Raod
 * @since: 2021-12-16
 */
public class DateSerializer extends JsonSerializer<Date> {

    private final String pattern;

    private String timezone;

    public DateSerializer(String pattern, String timezone) {
        super();
        this.pattern = pattern;
        this.timezone = timezone;
    }

    @Override
    public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (null == date) {
            return;
        }
        String time;
        //针对yyyy-MM或者yyyy-MM-dd这种，不做时区转换
        if (GaeaConstant.MOUTH_PATTERN.equals(pattern) || GaeaConstant.DATE_PATTERN.equals(pattern)) {
            time = GaeaDateUtils.DateToString(date, pattern);
        }else {
            TimeZone timeZone;
            if (StringUtils.isNotBlank(UserContentHolder.getTimeZone())) {
                timeZone = TimeZone.getTimeZone(UserContentHolder.getTimeZone());
            }else {
                timeZone = TimeZone.getDefault();
            }
            //将java机器所在时区转化为浏览器访问时区
            time = GaeaDateUtils.javaTimeToSourceTime(date, pattern, timeZone);
        }

        jsonGenerator.writeString(time);
    }

}
